const {
	Controller
} = require("uni-cloud-router");
const {
	success,
	fail,
	verify_token,
	build_token,
	create_uuid,
	encrypt,
	decrypt,
	isFieldExist,
	whereObj,
	isHttpMethod,
	isAdmin,
	isSuperAdmin,
	isAuthorities,
	
} = require('mh-utils');
//静态配置
const createConfig = require('uni-config-center')
const envCfg = createConfig({
	pluginId: 'env'
}).config()

module.exports = class RoleController extends Controller {
	// [sys:role:list, sys:role:add, sys:role:update, sys:role:delete]
	
	/**
	 * 分页查询
	 */
	async page() {
		const {
			ctx,
			service,
		} = this;
		const dbJQL = ctx.event.dbJQL;
		dbJQL.setUser({
			role: ['admin']
		})
		if(isHttpMethod(ctx, 'GET')){
			if(!isAdmin(ctx) && !isSuperAdmin(ctx)){
				if(!isAuthorities(ctx, 'sys:role:list')) {
					return fail({
						code: 1,
						message: '该用户无权限'
					})
				}
			}
			try{
				var where = "";
				
				// 查询条件
				var roleName = ctx.data.roleName;
				var roleCode = ctx.data.roleCode;
				var comments = ctx.data.comments;
				
				var sort = ctx.data.sort || null;
				var order = ctx.data.order || 'asc';
				if (isFieldExist(roleName)) {
					where = whereObj({where,query:`${new RegExp(roleName,'i')}.test(roleName)`});
				}
				if (isFieldExist(roleCode)) {
					where = whereObj({where,query:`${new RegExp(roleCode,'i')}.test(roleCode)`});
				}
				if (isFieldExist(comments)) {
					where = whereObj({where,query:`${new RegExp(comments,'i')}.test(comments)`});
				}
				//super超管能查看所有租户的用户
				if(!isSuperAdmin(ctx)){
					where = whereObj({where,query:`tenantId=='${ctx.auth.tenantId}'`});
				}
				where = whereObj({where,query:`deleted != 1`});
				
				// 分页
				var page = ctx.data.page || 1;
				var limit = ctx.data.limit || 500;
				var result = await dbJQL.collection("mh-sys-role")
					.where(`${where}`)
					.orderBy(`${sort}`, `${order}`)
					.skip((page*1 - 1) * limit)
					.limit(limit*1)
					.get({
						getCount: true
					})
				if(!result.data){
					return fail({
						code: 1,
						message: '操作失败'
					})
				}
				return success({
					code: 0,
					data: {
						list: result.data.map(item=>{
							return {
								...item,
								password: null,
							}
						}),
						count: result.count,
					}
				})
			}catch(e){
				uniCloud.logger.error(e)
				return fail({
					code: 500,
					data: e,
					message: e.errMsg
				})
			}
		}
	}
	
	/**
	 * 获取全部角色，非Super需要过滤掉管理员角色
	 */
	async list(){
		const {
			ctx,
			service,
		} = this;
		const dbJQL = ctx.event.dbJQL;
		dbJQL.setUser({
			role: ['admin']
		})
		if(isHttpMethod(ctx, 'GET')){
			if(!isAdmin(ctx) && !isSuperAdmin(ctx)){
				if(!isAuthorities(ctx, 'sys:role:list')) {
					return fail({
						code: 1,
						message: '该用户无权限'
					})
				}
			}
			try{
				var where = '';
				if (!isSuperAdmin(ctx)) {
					// 非Super只能查自己租户下的非管理员角色
					where = whereObj({where,query:`tenantId=='${ctx.auth.tenantId}'`});
					where = whereObj({where,query:`isAdmin==0`});
				}
				where = whereObj({where,query:`deleted != 1`});
				
				var result = await dbJQL.collection("mh-sys-role")
					.where(`${where}`)
					.get()
				if(result.data){
					return success({
						code: 0,
						data: result.data
					})
				}
				return fail({
					code: 1,
				})
			}catch(e){
				uniCloud.logger.error(e)
				return fail({
					code: 500,
					data: e,
					message: e.errMsg
				})
			}
		}
	}
	
	/**
	 * 新增
	 * @example data
	 */
	async add() {
		const {
			ctx,
			service,
		} = this;
		const dbJQL = ctx.event.dbJQL;
		dbJQL.setUser({
			role: ['admin']
		})
		if(isHttpMethod(ctx, 'POST')){
			if(!isAdmin(ctx) && !isSuperAdmin(ctx)){
				if(!isAuthorities(ctx, 'sys:role:add')) {
					return fail({
						code: 1,
						message: '该用户无权限'
					})
				}
			}
			try{
				delete ctx.data._id;
				var result = await dbJQL.collection("mh-sys-role")
					.add({
						...ctx.data,
						"createUserId": ctx.auth.loginUserId,
						"tenantId": ctx.data.tenantId?  ctx.data.tenantId: ctx.auth.tenantId,
					})
				if(result.id) {
					return success({
						code: 0,
						message: '操作成功'
					})
				}else{
					return fail({
						code: 1,
						message: '操作失败'
					})
				}
			}catch(e){
				uniCloud.logger.error(e)
				return fail({
					code: 500,
					data: e,
					message: e.errMsg
				})
			}
		}
	}
	
	/**
	 * 修改
	 * @example data
	 */
	async update() {
		const {
			ctx,
			service,
		} = this;
		const dbJQL = ctx.event.dbJQL;
		dbJQL.setUser({
			role: ['admin']
		})
		if(isHttpMethod(ctx, 'PUT')){
			if(!isAdmin(ctx) && !isSuperAdmin(ctx)){
				if(!isAuthorities(ctx, 'sys:role:update')) {
					return fail({
						code: 1,
						message: '该用户无权限'
					})
				}
				if(ctx.auth.loginUserId != ctx.data.createUserId) {
					return fail({
						code: 1,
						message: '不可操作非本人数据'
					})
				}
			}
			try{
				var roleId = ctx.data._id;
				if(!roleId) return fail({
					code: 1,
					message: '参数无效'
				})
				delete ctx.data._id; //_id带到查询数据库会报错
				delete ctx.data.tenantId;
				var result = await dbJQL.collection("mh-sys-role")
					.doc(roleId)
					.update({
						...ctx.data,
						updateTime: new Date().getTime()
					})
				if(result.updated > 0) {
					return success({
						code: 0,
						message: '操作成功'
					})
				}else{
					return fail({
						code: 1,
						message: '操作失败'
					})
				}
			}catch(e){
				uniCloud.logger.error(e)
				return fail({
					code: 500,
					data: e,
					message: e.errMsg
				})
			}
		}
	}
	
	/**
	 * 删除
	 * @example ?_id=111111&roleCode=user&createUserId=2222222
	 */
	async remove() {
		const {
			ctx,
			service,
		} = this;
		const dbJQL = ctx.event.dbJQL;
		dbJQL.setUser({
			role: ['admin']
		})
		if(isHttpMethod(ctx, 'DELETE')){
			if(!isAdmin(ctx) && !isSuperAdmin(ctx)){
				if(!isAuthorities(ctx, 'sys:role:delete')) {
					return fail({
						code: 1,
						message: '该用户无权限'
					})
				}
				if(ctx.auth.loginUserId != ctx.query.createUserId) {
					return fail({
						code: 1,
						message: '不可操作非本人数据'
					})
				}
			}
			
			try{
				var roleId = ctx.query._id;
				var roleCode = ctx.query.roleCode;
				if(!roleId) return fail({
					code: 1,
					message: '参数无效'
				})
				// 角色是否被使用
				var user = await dbJQL.collection("mh-sys-user")
					.where(`roleCodes == '${roleCode}' && deleted != 1`)
					.get()
				if(user.data.length > 0) return fail({
					code: 1,
					message: '该角色不可删除，正在被使用'
				})
				//删除
				var result = await dbJQL.collection("mh-sys-role")
					.doc(roleId)
					.update({
						deleted: 1,
						updateTime: new Date().getTime()
					})
				if(result.updated > 0) {
					return success({
						code: 0,
						message: '操作成功'
					})
				}else{
					return fail({
						code: 1,
						message: '操作失败'
					})
				}
			}catch(e){
				uniCloud.logger.error(e)
				return fail({
					code: 500,
					data: e,
					message: e.errMsg
				})
			}
		}
	}
	
	/**
	 * 批量删除
	 * @example ?_id=1,2,3&createUserId=8,8,8
	 */
	async removeBatch() {
		const {
			ctx,
			service,
		} = this;
		const dbJQL = ctx.event.dbJQL;
		dbJQL.setUser({
			role: ['admin']
		})
		if(isHttpMethod(ctx, 'DELETE')){
			if(!isAdmin(ctx) && !isSuperAdmin(ctx)){
				if(!isAuthorities(ctx, 'sys:role:delete')) {
					return fail({
						code: 1,
						message: '该用户无权限'
					})
				}
				var createUserIdArr = ctx.query.createUserId.split(',')
				for(var i=0; i<createUserIdArr.length; i++){
					if(ctx.auth.loginUserId != createUserIdArr[i]){
						return fail({
							code: 1,
							message: '不可操作非本人的数据'
						})
					}
				}
			}
			try{
				var _ids = ctx.query._id.split(',')
				var roleCode = ctx.query.roleCode.split(',')
				if(_ids.length == 0) return fail({
					code: 1,
					message: '参数无效'
				})
				
				// 角色是否被使用
				for(var i=0; i<roleCode.length; i++){
					var user = await dbJQL.collection("mh-sys-user")
						.where(`roleCodes == '${roleCode[i]}'`)
						.get()
					if(user.data.length > 0) return fail({
						code: 1,
						message: roleCode[i]+'编码的角色，不可删除，正在被使用'
					})
				}
				
				//删除
				var result = await dbJQL.collection("mh-sys-role")
					.where(`in(_id, ${JSON.stringify(_ids)})`)
					.update({
						deleted: 1,
						updateTime: new Date().getTime()
					})
				if(result.updated > 0) {
					return success({
						code: 0,
						message: '操作成功'
					})
				}else{
					return fail({
						code: 1,
						message: '操作失败'
					})
				}
			}catch(e){
				uniCloud.logger.error(e)
				return fail({
					code: 500,
					data: e,
					message: e.errMsg
				})
			}
		}
	}
	
	/**
	 * 根据roleId查询MenuIds
	 * @example ?roleId=111
	 */
	async getRoleMenuIds() {
		const {
			ctx,
			service,
		} = this;
		const dbJQL = ctx.event.dbJQL;
		dbJQL.setUser({
			role: ['admin']
		})
		if(isHttpMethod(ctx, 'GET')){
			if(!isAdmin(ctx) && !isSuperAdmin(ctx)){
				if(!isAuthorities(ctx, 'sys:role:list')) {
					return fail({
						code: 1,
						message: '该用户无权限'
					})
				}
			}
			try{
				var result = await dbJQL.collection("mh-sys-role")
					.doc(`${ctx.data.roleId}`)
					.get({
						getOne: true
					})
				if(result.data){
					return success({
						code: 0,
						data: result.data.menuIds,
					})
				}
				return fail({
					code: 1,
				})
			}catch(e){
				uniCloud.logger.error(e)
				return fail({
					code: 500,
					data: e,
					message: e.errMsg
				})
			}
		}
	}
	
	/**
	 * 设置roleId新的MenuIds
	 * @example data={roleId, menuIds, createUserId}
	 */
	async setRoleMenuIds() {
		const {
			ctx,
			service,
		} = this;
		const dbJQL = ctx.event.dbJQL;
		dbJQL.setUser({
			role: ['admin']
		})
		if(isHttpMethod(ctx, 'PUT')){
			if(!isAdmin(ctx) && !isSuperAdmin(ctx)){
				if(!isAuthorities(ctx, 'sys:user:update')) {
					return fail({
						code: 1,
						message: '该用户无权限'
					})
				}
				if(ctx.auth.loginUserId != ctx.data.createUserId) {
					return fail({
						code: 1,
						message: '不可操作非本人数据'
					})
				}
			}
			try{
				var result = await dbJQL.collection("mh-sys-role")
					.doc(`${ctx.data.roleId}`)
					.update({
						menuIds: ctx.data.menuIds,
						updateTime: new Date().getTime(),
					})
				if(result.updated > 0) {
					return success({
						code: 0,
						message: '操作成功'
					})
				}else{
					return fail({
						code: 1,
						message: '操作失败'
					})
				}
			}catch(e){
				uniCloud.logger.error(e)
				return fail({
					code: 500,
					data: e,
					message: e.errMsg
				})
			}
		}
	}
	
	
	
	
};
